﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Validation;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AccManagerKw.Common;
using DataAccess;
using Model;
using Model.Interfaces;
using Utilities;

namespace AccManagerKw.Masters.Accounts
{
    public partial class FrmAccountMaster : FrmBaseMaster, ICrud
    {
        private ClsCommonFn _oCommFn = new ClsCommonFn();
        private ClsDataFn _oDataFn = new ClsDataFn();
        private AccountMaster _row;
        public FrmAccountMaster()
        {
            InitializeComponent();
        }

        private void FrmAccountMaster_Shown(object sender, EventArgs e)
        {
            _oCommFn.GroupControl_Setting(gclMain);
            _oCommFn.GroupControl_Setting(gclOpen);
            _oCommFn.GridSetting(gvAccounts, gcAccounts);

            _oDataFn.SetDataSource(ClsGlobalEnums.EDataSourceType.AccGroups, lucGroups, "GroupName", "GrpId");
            _oDataFn.SetDataSource(ClsGlobalEnums.EDataSourceType.Cities, lucCities, "CityName", "CityId");
        }

        public bool OperationSave()
        {
            try
            {
                if (IsValid())
                {
                    if ((Mode == ClsGlobalVarz.Mode.Add || Mode == ClsGlobalVarz.Mode.Edit) &&
                        _oCommFn.ValidateCrud(Mode))
                    {
                        OperationAccount();
                        _oCommFn.MsgBoxCrud(Mode);
                        return true;
                    }
                    else if (Mode != ClsGlobalVarz.Mode.Add && Mode != ClsGlobalVarz.Mode.Edit)
                    {
                        _oCommFn.WarningMsg("Check Mode");
                        return false;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                _oCommFn.TryCatchErrorMsg(ex.Message);
                return false;
            }
        }

        private void OperationAccount()
        {
            using (var context = new AccManagerEntities())
            {
                var oAccMaster = new AccountMaster();
                if (Mode == ClsGlobalVarz.Mode.Add)
                {
                    oAccMaster.AccId = context.AccountMasters.ToList().Count > 0
                        ? context.AccountMasters.Max(x => x.AccId) + 1 : 1;
                }
                else if (Mode == ClsGlobalVarz.Mode.Edit)
                {
                    oAccMaster = context.AccountMasters.Single(x => x.AccId == _row.AccId);
                }
                oAccMaster.AccCode = txtCode.Text;
                oAccMaster.AccName = txtName.Text;
                oAccMaster.GrpId = lucGroups.Value;
                oAccMaster.Address = txtAddress.Text;
                oAccMaster.CityId = lucCities.Value;
                oAccMaster.OpBalance = txtOpBalance.ValueDec;
                oAccMaster.OpBalType = cbeOpBalType.Value;
                oAccMaster.MobileNo = txtMobileNo.ValueDec;
                oAccMaster.MobileNo2 = txtMobileNo2.ValueDec;
                oAccMaster.PhoneNo = txtPhoneNo.ValueDec;
                oAccMaster.PhoneNo2 = txtPhoneNo2.ValueDec;
                oAccMaster.Fax = txtFaxNo.ValueDec;
                oAccMaster.EmailId = txtEmailId.Text;

                if (Mode == ClsGlobalVarz.Mode.Add)
                {
                    oAccMaster.IsActive = true;
                    context.AccountMasters.Add(oAccMaster);
                }
                try
                {
                    context.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                            eve.Entry.Entity.GetType().Name, eve.Entry.State);
                        foreach (var ve in eve.ValidationErrors)
                        {
                            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                ve.PropertyName, ve.ErrorMessage);
                        }
                    }
                    throw;
                }
            }
        }

        public void OperationOpen()
        {
            gclOpen.BringToFront();
            var context = new AccManagerEntities();
            gcAccounts.DataSource = context.AccountMasters.Where(x => x.IsActive).ToList();
        }
        private void gvAccounts_DoubleClick(object sender, EventArgs e)
        {
            _row = (AccountMaster)gvAccounts.GetFocusedRow();
            txtCode.Text = _row.AccCode;
            txtName.Text = _row.AccName;
            lucGroups.EditValue = _row.GrpId;
            txtAddress.Text = _row.Address;
            lucCities.EditValue = _row.CityId;
            txtOpBalance.ValueDec = _row.OpBalance;
            cbeOpBalType.Value = _row.OpBalType;
            txtMobileNo.ValueDec = _row.MobileNo;
            txtMobileNo2.ValueDec = _row.MobileNo2;
            txtPhoneNo.ValueDec = _row.PhoneNo;
            txtPhoneNo2.ValueDec = _row.PhoneNo2;
            txtFaxNo.ValueDec = _row.Fax;
            txtEmailId.Text = _row.EmailId;

            _oCommFn.DisableControls(gclMain, true);
            gclMain.BringToFront();
        }
        public void OperationEdit()
        {
            if (_oCommFn.ValidateOpenRecord(_row.AccId))
            {
                _oCommFn.DisableControls(gclMain, false);
                SetMode(ClsGlobalVarz.Mode.Edit);
            }
        }

        public bool OperationDelete()
        {
            try
            {
                if (_oCommFn.ValidateOpenRecord(_row.AccId))
                {
                    SetMode(ClsGlobalVarz.Mode.Delete);
                    if (_oCommFn.ValidateCrud(Mode))
                    {
                        using (var context = new AccManagerEntities())
                        {
                            var oAccMaster = context.AccountMasters.Single(x => x.AccId == _row.AccId);
                            oAccMaster.IsActive = false;
                            context.SaveChanges();
                            _oCommFn.MsgBoxCrud(Mode);
                        }
                        return true;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                _oCommFn.TryCatchErrorMsg(ex.Message);
                return false;
            }
        }

        public void ResetData()
        {
            _oCommFn.ClearFields(this);
            _oCommFn.DisableControls(gclMain, false);
            gclMain.BringToFront();
            SetMode(ClsGlobalVarz.Mode.Add);
            _row = new AccountMaster();
        }

        public bool IsValid()
        {
            ccDxValidationProvider1.Validate();
            return ccDxValidationProvider1.GetInvalidControls().Count <= 0;
        }

        private void gvAccounts_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column == gColMobileNo)
            {
                if (e.DisplayText == "0")
                    e.DisplayText = "";
            }
        }


    }
}
